<script setup lang="ts">
/**
 * @name MeasuringInstrumentsManagement
 * @description 计量器具管理
 */

import {
  CopyDocument,
  Delete,
  Edit,
  Upload,
  View,
} from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import type { ComponentExposed } from 'vue-component-type-helpers'
import { cloneDeep } from 'lodash-es'
import {
  AssociationModal,
  FormModal,
} from './components'
import SearchForm from './components/SearchForm.vue'
import UploadModal from './components/UploadModal.vue'
import UploadInstrumentsModal from './components/UploadInstrumentsModal.vue'
import { AssociationModalV2, type AssociationModalV2Instance } from './components/AssociationModalV2'
import { MeasurePointTemplateModal, type MeasurePointTemplateModalInstance } from './components/MeasurePointTemplateModal'
import type { MeasurementLevelSumMap } from './type'
import {
  defaultFormData,
  defaultPagingParams,
} from './index'
import type { MeasuringToolsInfo, TableColumn } from '@/types'
import { measuringToolsApi } from '@/api'
import type { Point } from '@/components/ReadonlyPointTree/ReadonlyPointTree'
import { AnnexReportModal, type AnnexReportModalInstance } from './components/AnnexReportModal'

// ------------------use------------------
// #region
const { globalProperties, $confirm, $message }
  = useCurrentInstance()
const { withLoading, loading } = useDefineLoading()
const [tableData, setTableData] = useState<any[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [total, setTotal] = useState<number>(0)
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [selectPoint, setSelectPoint] = useState<Point | null>(null)
const [isView, setIsView] = useState(false)
const [measurementLevelSumMap, setMeasurementLevelSumMap]
  = useState<MeasurementLevelSumMap>({
    一级计量: 0,
    二级计量: 0,
    三级计量: 0,
  })
const [treeData, setTreeData] = useState([])
const columns: TableColumn<MeasuringToolsInfo>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '计量器具编号',
    prop: 'code',
  },
  {
    key: uuid(),
    label: '计量器具名称',
    prop: 'name',
  },
  {
    key: uuid(),
    label: '用能单元',
    prop: 'pointName',
  },
  {
    key: uuid(),
    label: '计量等级',
    prop: 'measurementLevelName',
    width: '120',
  },
  {
    key: uuid(),
    label: '安装位置',
    hidden: true,
    render({ row }) {
      return row.installationLocation ?? '---'
    },
  },
  {
    key: uuid(),
    label: '检定周期/天',
    prop: 'verificationCycle',
    hidden: true,
  },
  {
    key: uuid(),
    label: '下次检定时间',
    width: '150',
    hidden: true,
    render({ row }) {
      return row.nextVerificationDate
        ? formatTime(row.nextVerificationDate, 'YYYY-MM-DD')
        : '---'
    },
  },
  {
    key: uuid(),
    label: '检定报告',
    prop: 'annexUrl',
    width: '150',
    render({ row }) {
      if (row.annexCount && row.annexCount > 0) {
        return h(
          ElLink,
          {
            onClick: async () => {
              setToolId(row.id)
              setToolCode(row.code)
              setToolName(row.name)
              await nextTick()
              annexReportModalRef.value?.open()
            },
          },
          () => `查看报告` + `（${row.annexCount}）`,
        )
      }
      else {
        return '---'
      }
    },
  },
  {
    key: uuid(),
    label: '测点数量',
    render({ row }) {
      return h(
        'a',
        {
          href: 'javascript:void(0)',
          style: {
            color: 'var(--el-text-color-regular)',
          },
          onClick: () => {
            showAssociationModal(row)
          },
        },
        row.indicatorSum ?? 0,
      )
    },
  },
  {
    key: uuid(),
    label: '运行状态',
    prop: 'workingStatusName',
    hidden: true,
  },
  {
    key: uuid(),
    label: '接入状态',
    prop: 'accessStatus',
    hidden: true,
    render: ({ row }) => h('span', row.accessStatus == 1 ? '已接入' : '未接入'),
  },
  {
    key: uuid(),
    label: '生产厂家',
    prop: 'factory',
    hidden: true,
  },
  {
    key: uuid(),
    label: '检定日期',
    prop: 'verificationDate',
    hidden: true,
  },
  {
    key: uuid(),
    label: '计量精度等级',
    prop: 'accuracyLevel',
    hidden: true,
  },
  {
    key: uuid(),
    label: '测量范围',
    prop: 'measuringRange',
    hidden: true,
  },
  {
    key: uuid(),
    label: '计量器具类型',
    prop: 'typeName',
    hidden: true,
  },
  {
    key: uuid(),
    label: '清零时间',
    prop: 'clearTime',
    hidden: true,
  },
  {
    key: uuid(),
    label: '更换时间',
    prop: 'replacementTime',
    hidden: true,
  },
]

const modalRef = ref<ComponentExposed<typeof FormModal>>()
const uploadModalRef
  = ref<ComponentExposed<typeof UploadModal>>()

const associationModalRef
  = ref<ComponentExposed<typeof AssociationModal>>()
const pagingParams = ref<any>({
  ...defaultPagingParams,
})
const uploadInstrumentsModalRef = ref<InstanceType<typeof UploadInstrumentsModal>>()
const associationModalV2Ref = ref<AssociationModalV2Instance>()
const measurePointTemplateModalRef = ref<MeasurePointTemplateModalInstance>()

const annexReportModalRef = ref<AnnexReportModalInstance>()
const [toolCode, setToolCode] = useState('')
const [toolName, setToolName] = useState('')
const [toolId, setToolId] = useState(0)

function handleOpenMeasurePointTemplate() {
  measurePointTemplateModalRef.value?.open()
}

onBeforeMount(() => {
  getTreeData()
})

async function deleteData(row: MeasuringToolsInfo) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  if (row.annexName) {
    await minioApi.deleteFileById(row.annexName)
  }
  await measuringToolsApi.deleteMeasuringToolsById(row.id)
  globalProperties.$message.success('删除成功！')
  getTreeData()
  getTableData()
}

async function showEditDialog(row: MeasuringToolsInfo) {
  setIsView(false)
  getTreeData()
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑')
  setFormData({ ...defaultFormData, ...row })
}
async function showAddDialog(row?: MeasuringToolsInfo) {
  setIsView(false)
  getTreeData()
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增')
  const params = { ...defaultFormData }
  if (row) {
    const r = cloneDeep(row)
    Reflect.deleteProperty(r, 'id')
    Reflect.deleteProperty(r, 'code')
    Reflect.deleteProperty(r, 'annexName')
    Reflect.deleteProperty(r, 'annexUrl')
    Object.assign(params, r)
  }
  setFormData(params)
}

let getting = false
async function getTableData() {
  if (getting)
    return
  const params = {
    ...pagingParams.value,
    pointId: selectPoint.value?.id,
  }
  try {
    getting = true
    const { data: res } = await withLoading(
      measuringToolsApi.selectMeasuringToolsPage,
    )(params)
    setMeasurementLevelSumMap(res.measurementLevelSumMap)
    const { records = [], total = 0 } = res.ipage
    setTotal(total)
    setTableData(records ?? [])
  }
  finally {
    getting = false
  }
}
function success() {
  getTableData()
  modalRef.value?.close()
  $message.success('保存成功！')
}
function uploadSuccess() {
  getTableData()
}
async function showUploadModal(row: MeasuringToolsInfo) {
  uploadModalRef.value?.open()
  await nextTick()
  setFormData({ ...defaultFormData, ...row })
}
async function showAssociationModal(
  row: MeasuringToolsInfo,
) {
  setFormData({ ...defaultFormData, ...row })
  await nextTick()
  // associationModalRef.value?.open()
  associationModalV2Ref.value?.open()
}
async function handleClickNode(o: Point) {
  await setSelectPoint(o)
  await getTableData()
}
async function showViewModal(row: MeasuringToolsInfo) {
  setIsView(true)
  getTreeData()
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('查看')
  setFormData({ ...defaultFormData, ...row })
}
async function getTreeData() {
  const { data: res }
    = await measuringToolsApi.selectMeasuringToolsList()
  setTreeData(res ?? ([] as any))
}
async function showUploadInstrumentsModal() {
  uploadInstrumentsModalRef.value?.open()
}

async function handleDownload() {
  const pointId = unref(selectPoint)?.id
  const containSub = unref(pagingParams).containSub
  const energyId = unref(pagingParams).energyId
  if (!pointId) {
    ElMessage.warning('请选择用能单元')
  }
  if (containSub == null) {
    ElMessage.warning('请选择是否包含下级')
  }
  if (pointId && containSub != null) {
    try {
      const { data } = await measuringToolsApi.exportMeasuringTools({
        pointId,
        containSub,
        energyId,
      })
      window.open(data?.url)
    }
    catch (e) {}
  }
}

provide('pointInfo', selectPoint)
provide('toolInfo', formData)
</script>

<template>
  <div class="padding-sm flex gap-col-sm container">
    <ReadonlyPointTree fire @click-node="handleClickNode" />
    <div
      class="flex-direction overflow flex-fillRemaining flex align-end"
    >
      <ViewTable
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :operate-width="240"
        custom-download
        @download="handleDownload"
      >
        <template #actions>
          <SearchForm
            v-model="pagingParams"
            :measurement-level-sum-map="
              measurementLevelSumMap
            "
            @search="getTableData"
            @reset="getTableData"
            @plus="showAddDialog"
            @upload="showUploadInstrumentsModal"
          />
        </template>
        <template #operate="{ row }">
          <TdButton
            title="编辑"
            :icon="Edit"
            type="primary"
            @click="showEditDialog(row)"
          />
          <TdButton
            title="删除"
            :icon="Delete"
            type="danger"
            @click="deleteData(row)"
          />
          <TdButton
            title="查看"
            :icon="View"
            type="success"
            @click="showViewModal(row)"
          />
          <TdButton
            title="复制"
            :icon="CopyDocument"
            type="warning"
            @click="showAddDialog(row)"
          />
          <TdButton
            title="上传报告"
            :icon="Upload"
            type="primary"
            @click="showUploadModal(row)"
          />
        </template>
      </ViewTable>

      <!-- 分页 -->
      <ListsPagination
        v-model:page-num="pagingParams.pageNumber"
        v-model:page-size="pagingParams.pageSize"
        :total="total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>
    <FormModal
      v-if="selectPoint?.id"
      ref="modalRef"
      v-model:data="formData"
      :is-view="isView"
      :point-id="selectPoint?.id"
      :title="formModalTitle"
      :tree-data="treeData"
      @success="success"
    />
    <UploadModal
      ref="uploadModalRef"
      :form-data="formData"
      @success="uploadSuccess"
    />
    <!-- 关联测点对话框 -->
    <AssociationModal
      ref="associationModalRef"
      :tools-data="formData"
      @close="getTableData"
    />
    <!-- 导入对话框 -->
    <UploadInstrumentsModal ref="uploadInstrumentsModalRef" @after-close="getTableData" />
    <!-- 关联指标对话框 -->
    <AssociationModalV2
      v-if="formData.energyCode && selectPoint?.pointCode && formData.code"
      ref="associationModalV2Ref"
      :energy-code="formData.energyCode"
      :point-code="selectPoint?.pointCode"
      :code="formData.code"
      :tools-id="formData.id"
      :point-id="selectPoint?.id"
      @save-success="getTableData"
      @open-measure-point-template="handleOpenMeasurePointTemplate"
    />
    <!-- 管理测点模板 -->
    <MeasurePointTemplateModal
      v-if="formData.energyCode && selectPoint?.pointCode && formData.code"
      ref="measurePointTemplateModalRef"
      :energy-code="formData.energyCode"
      :energy-name="formData.energyName"
      :point-code="selectPoint?.pointCode"
      :code="formData.code"
      :tools-id="formData.id"
      :point-id="selectPoint?.id"
    />

    <!-- 查看报告对话框 -->
    <AnnexReportModal
      v-if="toolCode && toolName && toolId"
      ref="annexReportModalRef"
      :tool-id="toolId"
      :tool-code="toolCode"
      :tool-name="toolName"
      @after-close="getTableData"
    />
  </div>
</template>
